package com.jeejam.product.service.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jeejam.framework.base.pojo.TreePager;
import com.jeejam.framework.base.service.impl.BaseServiceImpl;
import com.jeejam.product.dao.CategoryMapper;
import com.jeejam.product.pojo.Category;
import com.jeejam.product.service.CategoryService;

@Service
public class CategoryServiceImpl extends BaseServiceImpl implements CategoryService{
	
	private CategoryMapper categoryMapper;
	
	public CategoryMapper getCategoryMapper() {
		return categoryMapper;
	}
	
	@Resource
	public void setCategoryMapper(CategoryMapper categoryMapper) {
		this.categoryMapper = categoryMapper;
		this.baseMapper = categoryMapper;
	}

	@Override
	public List<Category> selectRoot() {
		return categoryMapper.selectRoot();
	}

	@Override
	public List<Category> selectChildren(int catId) {
		return categoryMapper.selectChildren(catId);
	}

	@Override
	public List<Category> selectRootByPage(int page,int pageSize) {
		int begin = (page-1)*pageSize;
		Map<String, Serializable> params = new HashMap<String, Serializable>();
		params.put("begin", begin);
		params.put("pageSize", pageSize);
		return categoryMapper.selectRootByPage(params);
	}

	@Override
	public TreePager getTreePager(int currentPage, int pageSize) {
		TreePager pager = new TreePager();
		
		int totalGroupNum = categoryMapper.countsWithRoot();
		int totalNum = baseMapper.counts();
		int totalPage = totalGroupNum % pageSize == 0 ? totalGroupNum / pageSize : totalGroupNum / pageSize + 1;
		pager.setTotalGroupNum(totalGroupNum);
		pager.setTotalNum(totalNum);
		pager.setTotalPage(totalPage);
		pager.setCurrentPage(currentPage);
		pager.setPageSize(pageSize);
		return pager;
	}

	@Override
	public int countsWithRoot() {
		return categoryMapper.countsWithRoot();
	}

	@Override
	public List<Category> showIndex() {
		return categoryMapper.showIndex();
	}

	@Override
	public void deleteWithChildren(int id) {
		categoryMapper.deleteWithChildren(id);
	}

	@Override
	public List<Category> selectSubChildren(int parentId) {
		return categoryMapper.selectSubChildren(parentId);
	}

	@Override
	public List<Category> selectRootWithoutChildren() {
		return categoryMapper.selectRootWithoutChildren();
	}

	@Override
	public Category selectRootByCategoryId(int catId) {
		Category current = categoryMapper.select(catId);
		if(current.getParentId() != 0){
			Category root = categoryMapper.select(current.getParentId());
			root.setCategories(categoryMapper.selectChildren(root.getId()));
			return root;
		}else{
			current.setCategories(categoryMapper.selectChildren(catId));
			return current;
			
		}
	}

}
